package com.vshop.framework.mybatisflex.autoconfig;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.core.query.QueryColumnBehavior;
import com.mybatisflex.spring.boot.ConfigurationCustomizer;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import com.vshop.framework.core.util.YmlPropertySourceFactory;
import com.vshop.framework.mybatisflex.listener.EntityInsertListener;
import com.vshop.framework.mybatisflex.listener.EntityLogicDeleteListener;
import com.vshop.framework.mybatisflex.listener.EntityUpdateListener;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.Serializable;

@RequiredArgsConstructor
@Slf4j
@AutoConfiguration
@EnableTransactionManagement(proxyTargetClass = true)
@EnableConfigurationProperties(MyBatisFlexExtensionProperties.class)
@PropertySource(value = "classpath:default-mybatis-flex.yml", factory = YmlPropertySourceFactory.class)
public class MyBatisFlexAutoConfig implements ConfigurationCustomizer, MyBatisFlexCustomizer {
    @PostConstruct
    public void postConstruct() {
        log.info("初始化 MyBatisFlexAutoConfig");
    }

    static {
        // 关闭全局null参数忽略设置
        QueryColumnBehavior.setIgnoreFunction(QueryColumnBehavior.IGNORE_BLANK);
        QueryColumnBehavior.setSmartConvertInToEquals(true);
    }

    private final MyBatisFlexExtensionProperties properties;


    @Override
    public void customize(FlexConfiguration flexConfiguration) {

    }

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        // 注册全局数据填充监听器
        flexGlobalConfig.registerInsertListener(new EntityInsertListener(), Serializable.class);
        flexGlobalConfig.registerUpdateListener(new EntityUpdateListener(), Serializable.class);

        // 开启审计功能
        AuditManager.setAuditEnable(properties.isEnableAudit());
        if (properties.isEnableSqlPrint()) {
            // 开启sql打印默认会开启sql审计
            AuditManager.setAuditEnable(true);
            //设置 SQL 审计收集器
            AuditManager.setMessageCollector(auditMessage ->
                    log.info("\u001B[35m" + "SQL 执行时间：{} ms \u001B[0m" + " \u001B[34m" + "语句: {} \u001B[0m" + "\n {}",
                            auditMessage.getElapsedTime(),
                            auditMessage.getFullSql(),
                            auditMessage)
            );
        }
    }

    @Bean
    public EntityLogicDeleteListener entityLogicDeleteListener() {
        return new EntityLogicDeleteListener();
    }
}
